//
//  AMapHomeViewController.swift
//  AMapTest
//
//  Created by haisheng huang on 15/11/6.
//  Copyright © 2015年 haisheng huang. All rights reserved.
//

import UIKit
import MapKit

let reuseIdentifier: String = "annotationReuseIdentifier"

class AMapHomeViewController: UIViewController, MAMapViewDelegate, UITextFieldDelegate, AMapSearchDelegate, TabBarViewDelegate {

    @IBOutlet weak var amapView: MAMapView!
    @IBOutlet weak var textSuperView: UIView!
    @IBOutlet weak var textField: UITextField!
    
    var searchManager: AMapSearchAPI?
    var isLocatingCity: Bool? = false
    var currentCity: String? = "深圳市"
    
    var tabBar: TabBarView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.title = "地图导航"
    
        //let mapView: MAMapView = MAMapView(frame: CGRectMake())
        self.amapView.delegate = self
        self.amapView.showsUserLocation = true
        self.amapView.distanceFilter = 1000.0
        self.amapView.desiredAccuracy = 1000.0
        //self.amapView.userTrackingMode = MAUserTrackingMode.Follow
        //print("maxLevel:\(self.amapView.maxZoomLevel), minLevel:\(self.amapView.minZoomLevel)")
        self.amapView.setZoomLevel(16.3, animated: true)
        self.amapView.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)
        
        self.searchManager = AMapSearchAPI()
        AMapSearchServices.sharedServices().apiKey = AMapAPIKeyConfigure.getAPIKey()
        self.searchManager?.delegate = self
        
        //添加tabbar
        self.addTabBarView()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        

    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        
    }
    

    /********* MAMapViewDelegate **********/
    
    func mapView(mapView: MAMapView!, didUpdateUserLocation userLocation: MAUserLocation!, updatingLocation: Bool) {
        
        if updatingLocation {
            print("latitude : \(userLocation.coordinate.latitude),longitude: \(userLocation.coordinate.longitude)")
            if self.isLocatingCity == false {
                let reGeoRequest: AMapReGeocodeSearchRequest = AMapReGeocodeSearchRequest()
                reGeoRequest.location = AMapGeoPoint.locationWithLatitude(CGFloat( userLocation.coordinate.latitude), longitude: CGFloat(userLocation.coordinate.longitude))
                self.searchManager?.AMapReGoecodeSearch(reGeoRequest)
                self.isLocatingCity = true
            }
        }
    }
    
    func mapView(mapView: MAMapView!, didChangeUserTrackingMode mode: MAUserTrackingMode, animated: Bool) {
        
    }
    
    func mapViewDidStopLocatingUser(mapView: MAMapView!) {
        
        print("mapViewDidStopLocatingUser")
        
    }
    
    func mapView(mapView: MAMapView!, annotationView view: MAAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
        
    }
    
    func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation is MAPointAnnotation {
            
            var annotationView: MAPinAnnotationView? = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier) as? MAPinAnnotationView
            
            if annotationView == nil {
                annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
            }
            annotationView!.canShowCallout = true
            annotationView!.draggable = true
            annotationView!.pinColor = MAPinAnnotationColor.Purple
            annotationView!.animatesDrop = true
            return annotationView
        }
        
        return nil
    }
    
    func mapView(mapView: MAMapView!, annotationView view: MAAnnotationView!, didChangeDragState newState: MAAnnotationViewDragState, fromOldState oldState: MAAnnotationViewDragState) {
        
    }
    
    func mapView(mapView: MAMapView!, didAddAnnotationViews views: [AnyObject]!) {
        print("views : \(views.count)")
    }
    
    func mapView(mapView: MAMapView!, didSelectAnnotationView view: MAAnnotationView!) {
        
    }
    
    /***************** UITextFieldDelegate *********************/
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        print("should return")
        
        textField.resignFirstResponder()
        self.searchSomething(textField.text)
        return true
    }
    
    func searchSomething(key: String?) {
        
        if key == "定位" {
            self.amapView.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)
        } else {
            print("user location :\(self.amapView.userLocation)")
            let coordinate: CLLocationCoordinate2D = self.amapView.userLocation.coordinate
            print("lat: \(coordinate.latitude), lon: \(coordinate.longitude)")
            
            
//            let nearbySearchRequest: AMapNearbySearchRequest = AMapNearbySearchRequest()
//            nearbySearchRequest.center = AMapGeoPoint.locationWithLatitude(CGFloat( coordinate.latitude), longitude: CGFloat(coordinate.longitude))
//            nearbySearchRequest.radius = 5000
//            nearbySearchRequest.searchType = AMapNearbySearchType.Liner
//            nearbySearchRequest.timeRange = 1800
//            nearbySearchRequest.limit = 30
//            
//            self.searchManager?.AMapNearbySearch(nearbySearchRequest)
            
//            let poiSearchRequest: AMapPOIKeywordsSearchRequest = AMapPOIKeywordsSearchRequest()
//            poiSearchRequest.city = self.currentCity
//            poiSearchRequest.keywords = key
//            self.searchManager?.AMapPOIKeywordsSearch(poiSearchRequest)
            
            let poiSearchRequest: AMapPOIAroundSearchRequest = AMapPOIAroundSearchRequest()
            poiSearchRequest.location = AMapGeoPoint.locationWithLatitude(CGFloat(self.amapView.userLocation.coordinate.latitude), longitude: CGFloat(self.amapView.userLocation.coordinate.longitude))
            poiSearchRequest.keywords = key
            poiSearchRequest.radius = 50000
            self.searchManager?.AMapPOIAroundSearch(poiSearchRequest)
        }
    }
    
    /******************* AMapSearchDelegate *********************/
    
    func AMapSearchRequest(request: AnyObject!, didFailWithError error: NSError!) {
        print("AMapSearchRequest --- didFailWithError \(error)")
    }
    
    func onPOISearchDone(request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        print("onPOISearchDone --- response.count:\(response.count)\n --- response.suggestion.keywords:\(response.suggestion.keywords)\n ---response.suggestion.cities:\(response.suggestion.cities)\n ---response.pois:\(response.pois.count)")
        
        self.amapView.removeAnnotations(self.amapView.annotations)
        
        for amappoi in response.pois {
            
            let tempPoi: AMapPOI = amappoi as! AMapPOI
            print("poi -- name:\(tempPoi.name) -- address:\(tempPoi.address) -- location:\(tempPoi.location.latitude)--\(tempPoi.location.longitude)")
            let pointAnnotation: MAPointAnnotation = MAPointAnnotation()
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(Double(tempPoi.location.latitude), Double(tempPoi.location.longitude))
            pointAnnotation.title = tempPoi.name
            
            if tempPoi.address == nil {
                pointAnnotation.subtitle = self.currentCity
            } else {
                pointAnnotation.subtitle = tempPoi.address
            }
            self.amapView.addAnnotation(pointAnnotation)
        }
        
        self.zoomMapViewToFitAnnotations(self.amapView, animated: true)
        
    }
    
    func onNearbySearchDone(request: AMapNearbySearchRequest!, response: AMapNearbySearchResponse!) {
        
        print("response: \(response)")
    }
    
    func onInputTipsSearchDone(request: AMapInputTipsSearchRequest!, response: AMapInputTipsSearchResponse!) {
        
    }
    
    func onGeocodeSearchDone(request: AMapGeocodeSearchRequest!, response: AMapGeocodeSearchResponse!) {
        
    }
    
    func onReGeocodeSearchDone(request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        print("onReGeocodeSearchDone --- \(response.regeocode.formattedAddress)")
        print("onReGeocodeSearchDone --- \(response.regeocode.addressComponent.city)")
        self.currentCity = response.regeocode.addressComponent.city
    }
    
    
    private func zoomMapViewToFitAnnotations(mapView: MAMapView, animated: Bool) {
    
        let annotations: NSArray = mapView.annotations
        
        let count: Int = annotations.count
        
        if count == 0 {
            return;
        }
        
        var points = [MKMapPoint](count: count, repeatedValue: MKMapPoint())
        var coordinate: CLLocationCoordinate2D
        
        for i in 0...annotations.count-1 {
            coordinate = (annotations[i] as! MAAnnotation).coordinate
            points[i] = MKMapPointForCoordinate(coordinate)
        }
        
        let mapRect: MKMapRect = MKPolygon(points: UnsafeMutablePointer(points), count: count).boundingMapRect
        var region: MKCoordinateRegion = MKCoordinateRegionForMapRect(mapRect)
        
        region.span.latitudeDelta *= ANNOTATION_REGION_PAD_FACTOR
        region.span.longitudeDelta *= ANNOTATION_REGION_PAD_FACTOR
        
        if region.span.latitudeDelta > MAX_DEGREES_ARC {
            region.span.latitudeDelta = MAX_DEGREES_ARC
        }
        
        if region.span.longitudeDelta > MAX_DEGREES_ARC {
            region.span.longitudeDelta = MAX_DEGREES_ARC
        }
        
        if region.span.latitudeDelta < MINIMUM_ZOOM_ARC {
            region.span.latitudeDelta = MINIMUM_ZOOM_ARC
        }
        
        if region.span.longitudeDelta < MINIMUM_ZOOM_ARC {
            region.span.longitudeDelta = MINIMUM_ZOOM_ARC
        }
        
        if count == 1 {
            region.span.latitudeDelta = MINIMUM_ZOOM_ARC
            region.span.longitudeDelta = MINIMUM_ZOOM_ARC
        }
        
        mapView.setRegion(MACoordinateRegion(center: region.center, span: MACoordinateSpanMake(region.span.latitudeDelta, region.span.longitudeDelta)), animated: true)
        
    }
    
    private func addTabBarView() {
        
        let highlightColor: UIColor = UIColor(colorLiteralRed: 0.0, green: 193.0/255.0, blue: 200.0/255.0, alpha: 1.0)
        let normalColor: UIColor = UIColor(colorLiteralRed: 70.0/255.0, green: 74.0/255.0, blue: 85.0/255.0, alpha: 1.0)
        let items:NSArray = [[TabItemInfoKeyTitle:"医院",
            TabItemInfoKeyNormalImage:"医院-2",
            TabItemInfoKeyHighlightedImage:"医院-1",
            TabItemInfoKeyNormalColor:normalColor,
            TabItemInfoKeyHighlightedColor:highlightColor],
            [TabItemInfoKeyTitle:"药店",
                TabItemInfoKeyNormalImage:"药店-2",
                TabItemInfoKeyHighlightedImage:"药店-1",
                TabItemInfoKeyNormalColor:normalColor,
                TabItemInfoKeyHighlightedColor:highlightColor],
            [TabItemInfoKeyTitle:"社康",
                TabItemInfoKeyNormalImage:"社康-2",
                TabItemInfoKeyHighlightedImage:"社康-1",
                TabItemInfoKeyNormalColor:normalColor,
                TabItemInfoKeyHighlightedColor:highlightColor]]
        
        let frame:CGRect = CGRectMake(0,self.view.frame.size.height - 49, UIScreen.mainScreen().bounds.width, 49);
        
        let tabBar:TabBarView = TabBarView(frame: frame, items: items, barStyle: TabItemStyle.TitleAndIcon, selectedIndex: 0)
        
        tabBar.delegate = self
        
        self.view.addSubview(tabBar)
        
        self.tabBar = tabBar
        
    }
    
    /********************** TabBarViewDelegate ****************************/
    
    func shouldSelectAtIndex(index: Int, view: TabBarView) -> Bool {
        
        return true
    }
    
    func didSelectAtIndex(index: Int, view: TabBarView) {
        
        var keyword: String = "定位"
        
        switch index {
            
            case 0: keyword = "医院"
                    break
        
            case 1: keyword = "药店"
                    break
        
            case 2: keyword = "社康中心"
                    break
            
            default: break
            
        }
        
        self.searchSomething(keyword)
    }
}
